package net.csdn.business.facade;

import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.common.domain.PageDto;
import net.csdn.business.common.domain.request.MilepostSaveDto;
import net.csdn.business.common.domain.request.MilepostSaveMigrateDto;
import net.csdn.business.common.domain.request.MilepostSearchDto;
import net.csdn.business.common.domain.request.UserRegMigrateDto;
import net.csdn.business.common.domain.vo.MilepostVo;
import net.csdn.business.common.domain.vo.migrate.MigrateInfoLogVo;
import net.csdn.business.common.utils.JsonUtil;
import net.csdn.business.enums.MigrateEnum;
import net.csdn.business.enums.MileStoneStateEnum;
import net.csdn.business.pojo.AtomGitMileStone;
import net.csdn.business.pojo.AtomGitUser;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Component
public class MileStoneFacade {

    //private final MilepostFeignClient milepostFeignClient;
    private final UserFacade userFacade;
    private final MigrateFacade migrateFacade;
    @Value("${grpc.atomgit.anonymous:65f906eb7af38bb6ff80f4d8}")
    private String anonymous;



    private String queryMileStone(Long projectId, AtomGitMileStone atomGitMileStone){
        MilepostSearchDto milepostSearchDto = new MilepostSearchDto();
        milepostSearchDto.setKey(atomGitMileStone.getTitle());
        milepostSearchDto.setSourceId(projectId.toString());
        milepostSearchDto.setSourceType(2);
        milepostSearchDto.setPageNum(1);
        milepostSearchDto.setPageSize(100);
       // PageDto<MilepostVo> list = milepostFeignClient.getList(milepostSearchDto);
        PageDto<MilepostVo> list=null;
        if(list.getPageSize()>0){
            List<MilepostVo> result = list.getContent().stream().filter(milepostVo -> milepostVo.getGoalName().toLowerCase().equals(atomGitMileStone.getTitle().toLowerCase())).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(result)){
                return result.get(0).getObjectId();
            }
        }
        return null;
    }

    public void addMilePost(MilepostSaveMigrateDto migrateDto){
        MilepostSaveDto milepostSaveDto = new MilepostSaveDto();
        BeanUtils.copyProperties(migrateDto,milepostSaveDto);
        milepostSaveDto.setSourceId(migrateDto.getProjectId().toString());
        milepostSaveDto.setSourceType(2);
        String userId = userFacade.queryForMigrateUser(migrateDto.getCreator());
        if(StringUtils.isNotEmpty(userId)){
            milepostSaveDto.setCrrUserId(userId);
        }else{
            milepostSaveDto.setCrrUserId(anonymous);
        }
        //TODO save update migrateInfoLog
        MigrateInfoLogVo vo = migrateFacade.queryLog(MigrateEnum.MigrateInfoTypeEnum.MILESTONE.code, migrateDto.getOriginId(), migrateDto.getGroupPath(), migrateDto.getRepoId());
        if(ObjectUtils.isEmpty(vo.getId())){
            //需要 save
            //String objectId = milepostFeignClient.addMilePost(milepostSaveDto);
            String objectId =null;
            vo.setObjectId(objectId);
            vo.setStatus(MigrateEnum.Status.SUCCESS.code);
            migrateFacade.save(vo);
        }else{
            //需要 update
            milepostSaveDto.setGoalId(vo.getObjectId());
            //milepostFeignClient.updateMilePost(milepostSaveDto);
            vo.setStatus(MigrateEnum.Status.SUCCESS.code);
            migrateFacade.save(vo);
        }
    }

    public Integer importMileStone(Long repoId,String repoGroupName,String repoName, List<AtomGitMileStone> mileStoneList){
        String adminUid = userFacade.getAdminUserIdByProjectId(repoGroupName, repoName);
        List<MilepostSaveMigrateDto> migrateDtos = Lists.transform(mileStoneList, i->{
            MilepostSaveMigrateDto migrateDto = new MilepostSaveMigrateDto();
            migrateDto.setGoalName(i.getTitle());
            migrateDto.setGoalDesc(i.getDescription());
            migrateDto.setCreatedDate(new Date(i.getStartDate()*1000));
            migrateDto.setDeadline(new Date(i.getDueDate()*1000));
            migrateDto.setRepoId(String.valueOf(repoId));
            migrateDto.setOriginId(String.valueOf(i.getId()));
            migrateDto.setGroupPath(repoGroupName);
            migrateDto.setGoalStatus(MileStoneStateEnum.getStateName(i.getState()).migrateStateInt);
            UserRegMigrateDto userRegMigrateDto = new UserRegMigrateDto();
            AtomGitUser user = i.getCreator();
            userRegMigrateDto.setName(user.getName());
            userRegMigrateDto.setUsername(user.getUserName());
            userRegMigrateDto.setNickname(user.getName());
            //避免用户信息为空的情况
            userRegMigrateDto.setEmail(ObjectUtils.isEmpty(user.getEmail())?user.getUserName()+"@atomgit.com":user.getEmail());
            userRegMigrateDto.setPhone(user.getPhone());
            userRegMigrateDto.setExternalId(String.valueOf(user.getId()));
            //设置creator信息
            migrateDto.setCreator(userRegMigrateDto);
            return migrateDto;
        });
        return importMileStone(repoGroupName + "/" + repoName,adminUid, migrateDtos);
    }

    public Integer importMileStone(String reposityPath,String adminProjectId,List<MilepostSaveMigrateDto> migrateDtos){
        //ProjectVo projectVo = migrateFacade.getProjectDetailByPath(reposityPath);
        AtomicReference<Integer> succesNum = new AtomicReference<>(0);
       /* if(ObjectUtils.isEmpty(projectVo)){
            throw new BusinessException(ResultCodeEnum.RESOURCE_NOT_EXIST);
        }*/
        //Long reposityId = projectVo.getId();
        Long reposityId =null;
        migrateDtos.forEach(mileStone->{
            try {
                mileStone.setProjectId(reposityId);
                mileStone.setCrrUserId(adminProjectId);
                addMilePost(mileStone);
                succesNum.getAndSet(succesNum.get() + 1);
            } catch (Exception e) {
                log.error("addMilePost mileStone:{} error:{}", JsonUtil.toJsonString(mileStone), JsonUtil.toJsonString(e));
            }
        });
        return succesNum.get();
    }

}
